<template>
  <a-card :bordered="false" class="spin-wrap">
    <div class="spin-mask" v-if="loading">
      <a-spin />
    </div>

    <!-- 表单 -->
    <a-form :form="form" style="max-width: 500px; margin: 50px auto 30px;">
      <a-alert :closable="true" message="默认的初始提现密码为 000000" style="margin-bottom: 24px;" />

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="手机号码">
        <a-input placeholder="11 位手机号" :value="phone" name="mobile" disabled>
          <span slot="addonBefore">+86</span>
        </a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="验证码" class="x-check-wrap">
        <a-input
          type="text"
          class="get-captcha-wrap"
          placeholder="验证码"
          :maxLength="6"
          name="captcha"
          v-decorator="['captcha', validatorRules.captcha]"
        >
          <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
          <a-button
            class="getCaptcha"
            slot="addonAfter"
            size="default"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
            v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
          ></a-button>
        </a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="旧提现密码">
        <a-input
          type="password"
          placeholder="请输入旧提现密码"
          :maxLength="6"
          v-decorator="['oldpassword', validatorRules.oldpassword]"
        />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="新密码">
        <a-input
          type="password"
          :maxLength="6"
          placeholder="请输入新提现密码"
          v-decorator="['password', validatorRules.password]"
        />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="确认新密码">
        <a-input
          type="password"
          @blur="handleConfirmBlur"
          placeholder="请确认新提现密码"
          :maxLength="6"
          v-decorator="['confirmpassword', validatorRules.confirmpassword]"
        />
      </a-form-item>

      <a-form-item :wrapperCol="{ span: 24, offset: 5 }">
        <a-button type="primary" @click="onSubmit" :disabled="loading">修改</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { postAction } from '@/api/action'
import { updateWithdrawPwd } from '@/api/api'

export default {
  name: 'WithDrawPassword',
  data() {
    return {
      state: {
        time: 60,
        smsSendBtn: false
      },

      phone: this.$store.getters.userInfo.phone || '',
      loading: false,

      //校验规则
      validatorRules: {
        oldpassword: {
          rules: [
            {
              required: true,
              message: '请输入旧提现密码!'
            }
          ],
          validateTrigger: ['change', 'blur']
        },
        password: {
          rules: [
            {
              required: true,
              message: '请输入新提现密码!'
            },
            {
              validator: this.validateToNextPassword
            }
          ],
          validateTrigger: ['change', 'blur']
        },
        confirmpassword: {
          rules: [
            {
              required: true,
              message: '请确认新提现密码!'
            },
            {
              validator: this.compareToFirstPassword
            }
          ],
          validateTrigger: ['change', 'blur']
        },
        captcha: {
          rules: [{ required: true, message: '请输入验证码', whitespace: true }],
          validateTrigger: ['change', 'blur']
        }
      },

      confirmDirty: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      form: this.$form.createForm(this)
    }
  },

  created() {
    console.log('修改提现密码...')
  },

  methods: {
    /**
     * 提交表单
     */
    onSubmit() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          //获取参数
          var params = {
            mobile: that.phone,
            smscode: values.captcha,
            old_password: values.oldpassword,
            new_password: values.password,
            confirm_password: values.confirmpassword
          }
          console.log(params)

          //提交数据
          this.loading = true
          updateWithdrawPwd(params)
            .then(res => {
              that.loading = false
              if (res.code == 0) {
                that.updatePwdSucc()
                that.form.resetFields()
              } else {
                that.updatePwdFailed(res.msg)
              }
            })
            .catch(err => {
              this.loading = false
              this.requestFailed(err)
            })
        }
      })
    },

    /**
     * 获取短信验证码
     */
    getCaptcha(e) {
      e.preventDefault()
      this.state.smsSendBtn = true

      //倒计时60s
      let that = this
      let interval = window.setInterval(() => {
        if (that.state.time-- <= 0) {
          that.state.time = 60
          that.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)

      //获取参数
      const hide = this.$message.loading('验证码已发送..', 0)
      const params = {
        mobile: this.phone,
        smsmode: '2' //密码重置
      }

      postAction('/account/sms/send', params)
        .then(res => {
          if (res.code != 0) {
            that.updatePwdFailed(res.msg)
            setTimeout(hide, 0)
          }
          setTimeout(hide, 500)
        })
        .catch(err => {
          setTimeout(hide, 1)
          clearInterval(interval)
          this.state.time = 60
          this.state.smsSendBtn = false
          this.requestFailed(err)
        })
    },

    /**
     * 校验新提现密码
     */
    validateToNextPassword(rule, value, callback) {
      const form = this.form

      if (!value) {
        callback()
        return
      }

      let reg = /^(?=.*\d).{6,6}$/
      if (!reg.test(value)) {
        // 和特殊符号 大小写
        callback(new Error('密码由6位数字组成!'))
        return
      }

      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },

    /**
     * 确认密码
     */
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },

    /**
     * 确认密码焦点失去事件
     */
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },

    /**
     * 修改密码成功
     */
    updatePwdSucc() {
      this.$notification['success']({
        message: '操作成功',
        description: '密码修改成功',
        duration: 2
      })
    },

    /**
     * 修改密码失败
     */
    updatePwdFailed(msg) {
      this.$notification['error']({
        message: '操作失败',
        description: msg,
        duration: 2
      })
    },

    /**
     * 请求错误
     */
    requestFailed(err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).msg || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style scoped lang="scss">
.spin-wrap {
  .ant-card-body {
    position: relative;
  }

  .spin-mask {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
    z-index: 100;
    background: rgba($color: #fff, $alpha: 0.4);
  }
}

.getCaptcha {
  display: block;
  width: 100px;
  height: 30px;
  background: transparent;
  border: none;
  overflow: hidden;
  outline: none;
  color: #fff;
  background-color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 0 4px 4px 0;
}

.tip-msg {
  color: grey;
}

.ant-btn[disabled] {
  color: rgba(0, 0, 0, 0.25) !important;
  background-color: #f5f5f5 !important;
  border: none !important;
}
</style>

<style lang="scss">
.get-captcha-wrap {
  .ant-input-group-addon {
    padding: 0;
  }
}
</style>
